<?php
namespace app\admin\controller;

use app\admin\model\ExamPaper as ExamPaperModel;
use app\admin\model\ExamPaperQuestion as ExamPaperQuestionModel;
use app\admin\model\ExamQuestion as ExamQuestionModel;
use app\admin\validate\ExamPaper as ExamPaperValidate;

use app\common\controller\Backend;

class ExamPaper extends Backend
{
    // 试卷列表
    public function index(): void
    {
        $list = ExamPaperModel::order('id desc')->paginate(20);
        $this->success('', $list);
    }

    // 新增试卷
    public function add(): void
    {
        $data = $this->request->post();
        $validate = new ExamPaperValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['create_time'] = time();
        $data['update_time'] = time();
        $paper = ExamPaperModel::create($data);
        $this->success('添加成功', ['id'=>$paper->id]);
    }

    // 编辑试卷
    public function edit(): void
    {
        $id = $this->request->post('id');
        $data = $this->request->post();
        $validate = new ExamPaperValidate();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['update_time'] = time();
        ExamPaperModel::update($data, ['id'=>$id]);
        $this->success('修改成功');
    }

    // 删除试卷
    public function del(): void
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('参数错误');
        }
        ExamPaperModel::destroy($ids);
        ExamPaperQuestionModel::where('paper_id','in',$ids)->delete();
        $this->success('删除成功');
    }

    // 试卷详情
    public function detail($id)
    {
        $info = ExamPaperModel::find($id);
        if (!$info) {
            return json(['code'=>0,'msg'=>'试卷不存在']);
        }
        $questions = ExamPaperQuestionModel::where('paper_id',$id)->select();
        return json(['code'=>1,'msg'=>'','data'=>['info'=>$info,'questions'=>$questions]]);
    }

    // 组卷：保存题目
    public function saveQuestions($id)
    {
        $questions = input('post.questions',[]);
        ExamPaperQuestionModel::where('paper_id',$id)->delete();
        foreach($questions as $q){
            $q['paper_id'] = $id;
            ExamPaperQuestionModel::create($q);
        }
        // 更新题目数量和总分
        $count = count($questions);
        $score = array_sum(array_column($questions,'score'));
        ExamPaperModel::update(['question_count'=>$count,'total_score'=>$score],['id'=>$id]);
        return json(['code'=>1,'msg'=>'保存成功']);
    }

    // 获取题库（按类型分组）
    public function questionBank()
    {
        $type = $this->request->get('type', null);
        $page = (int)$this->request->get('page', 1);
        $pageSize = (int)$this->request->get('pageSize', 10);
        $q = trim($this->request->get('q', ''));

        if ($type) {
            $query = ExamQuestionModel::where('type', $type);
            if ($q !== '') {
                $query = $query->where('content', 'like', "%{$q}%")->whereOr('analysis', 'like', "%{$q}%");
            }
            $total = $query->count();
            $list = $query->order('id desc')->page($page, $pageSize)->select();
            return json(['code' => 1, 'msg' => '', 'data' => ['items' => $list, 'total' => $total]]);
        }

        // no type: return grouped full list (backward compatible)
        $list = ExamQuestionModel::order('id desc')->select();
        $grouped = [];
        foreach($list as $q){
            $grouped[$q['type']][] = $q;
        }
        return json(['code'=>1,'msg'=>'','data'=>$grouped]);
    }
}
